package cn.itcast.order.controller;

import cn.itcast.feign.client.ItemClient;
import cn.itcast.feign.client.UserClient;
import cn.itcast.hmall.pojo.item.Item;
import cn.itcast.hmall.pojo.order.Order;
import cn.itcast.hmall.pojo.order.OrderCreate;
import cn.itcast.hmall.pojo.order.OrderDetail;
import cn.itcast.order.mapper.OrderMapper;
import cn.itcast.order.service.OrderDetailService;
import cn.itcast.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("order")
@Slf4j
public class OrderController {
    @Autowired
    UserClient userClient;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    ItemClient itemClient;
    @Autowired
    private OrderService orderService;
    @Autowired
    OrderDetailService orderDetailService;
    @GetMapping("{orderId}")
    public Order selectById(@PathVariable("orderId") Long orderId){
        Order order = orderMapper.selectById(orderId);
        System.out.println(order);
        return order;
    }


    @PostMapping
    public String orderCreate(@RequestBody OrderCreate orderCreate){
        Item item = itemClient.findById(orderCreate.getItemId());
        Long totalFee=item.getPrice()*orderCreate.getNum();
        Order order=new Order();
        order.setStatus(1);
        order.setUserId(2l);
        order.setTotalFee(totalFee);
        order.setPaymentType(orderCreate.getPaymentType());
        Date date = new Date();
        order.setCreateTime(date);
        boolean save = orderService.save(order);
        Long orderId = order.getId();
        // 消息ID，需要封装到CorrelationData中
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        // 发送消息
        rabbitTemplate.convertAndSend("ttl.direct", "ttl", orderId, correlationData);
        // 记录日志
        log.info("发送消息成功");
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setItemId(orderCreate.getItemId());
        orderDetail.setOrderId(order.getId());
        orderDetail.setNum(orderCreate.getNum());
        Item byId = itemClient.findById(orderCreate.getItemId());
        orderDetail.setName(byId.getName());
        orderDetail.setSpec(byId.getSpec());
        orderDetail.setPrice(byId.getPrice());
        orderDetail.setImage(byId.getImage());
        orderDetail.setCreateTime(byId.getCreateTime());
        orderDetail.setUpdateTime(byId.getUpdateTime());
        orderDetailService.save(orderDetail);
        System.out.println(save+"----"+order);
        return order.getId().toString();
        }

    }

